package com.oj.system.service.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.oj.common.core.domain.LoginUser;
import com.oj.common.core.domain.R;
import com.oj.common.core.domain.vo.LoginUserVO;
import com.oj.common.core.enums.ResultCode;
import com.oj.common.core.enums.UserIdentity;
import com.oj.common.redis.service.RedisService;
import com.oj.common.security.exception.ServiceExpection;
import com.oj.common.security.service.TokenService;
import com.oj.system.domain.sysuser.SysUser;
import com.oj.system.domain.sysuser.dto.SysUserSaveDTO;
import com.oj.system.mapper.SysUserMapper;
import com.oj.system.service.sysuser.ISysUserService;
import com.oj.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @Description
 * @Author bin
 * @Date 2025/4/2
 */

@Service
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RedisService redisService;

    @Override
    public R<String> login(String userAccount, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getPassword,SysUser::getUserId,SysUser::getNickName)
                .eq(SysUser::getUserAccount, userAccount));
        if (sysUser == null){
            return R.fail(ResultCode.FAILED_USER_EXISTS);
        }
        if(!BCryptUtils.matchesPassword(password,sysUser.getPassword())){
            return R.fail(ResultCode.FAILED_LOGIN);
        }
        // 系统用户没有头像
        String token = tokenService.createToken(sysUser.getUserId(), UserIdentity.ADMIN.getValue(), secret,sysUser.getNickName(),null);
        return R.ok(token);
    }

    @Override
    public int add(SysUserSaveDTO sysUserSaveDTO) {
        List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));
        if (CollectionUtil.isNotEmpty(sysUsers)){
            //用户已经存在
            throw new ServiceExpection(ResultCode.FAILED_USER_EXISTS);
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
        //其他公有属性MybatisPlus自动填充
        return sysUserMapper.insert(sysUser);
    }

    @Override
    public R<LoginUserVO> info(String token) {
        LoginUser loginUser = tokenService.getLoginUser(token,secret);
        if(loginUser == null){
            return R.fail();
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        loginUserVO.setIdentity(loginUser.getIdentity());
        return R.ok(loginUserVO);
    }

    @Override
    public R<Void> logout(String token) {
        String redisTokenKey = tokenService.getRedisTokenKey(token, secret);
        if(redisService.hasKey(redisTokenKey)){
            if(redisService.deleteObject(redisTokenKey)){
                return R.ok();
            }
            return R.fail();
        }else {
            return R.fail();
        }
    }
}